package com.h2cloud.ThreadLocalTest;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.thymeleaf.util.ObjectUtils;

/**
 * @Package: com.h2cloud.ThreadLocalTest
 * @ClassName: RequestContext
 * @Author: h2cloud
 * @CreateTime: 2024/3/7 12:30 上午
 * @Description:
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RequestContext {

	private static final ThreadLocal<RequestContext> transmittableThreadLocal = new TransmittableThreadLocal();


	private static final RequestContext INSTANCE = new RequestContext();
	private RequestHeader requestHeader;


	public static void create(RequestHeader requestHeader) {
		transmittableThreadLocal.set(new RequestContext(requestHeader));
	}

	public static RequestContext current() {
		if (ObjectUtil.isNotEmpty(transmittableThreadLocal.get())) {
			return transmittableThreadLocal.get();
		} else {
			return INSTANCE;
		}
	}

	public static RequestHeader get() {
		return current().getRequestHeader();
	}

	public static void remove() {
		transmittableThreadLocal.set(null);
	}


	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	@ToString
	static class RequestHeader {
		private String requestUrl;
		private String requestType;
	}
}
